package com.dbf.site.client.message.presenter;

import com.dbf.site.client.ForumEventBus;
import com.dbf.site.client.message.MessageServiceAsync;
import com.dbf.site.client.message.model.MessageModel;
import com.dbf.site.client.message.ui.IMessageView;
import com.dbf.site.client.message.ui.MessageView;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;
import com.sencha.gxt.data.client.loader.RpcProxy;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.loader.DataReader;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoader;

@Presenter(view = MessageView.class)
public class MessagePresenter extends
		BasePresenter<IMessageView, ForumEventBus> implements
		IMessageView.IMessagePresenter {

	@Inject
	MessageServiceAsync service;
	private PagingLoader<PagingLoadConfig, PagingLoadResult<MessageModel>> loader = null;
    private ListStore<MessageModel> store = null;
    
    @SuppressWarnings( "unchecked" )
    @Override
    public void bind() {
    	final RpcProxy<PagingLoadConfig, PagingLoadResult<MessageModel>> rpxProxy = new RpcProxy<PagingLoadConfig, PagingLoadResult<MessageModel>>() {
	
			@Override
			public void load(PagingLoadConfig loadConfig,
					AsyncCallback<PagingLoadResult<MessageModel>> callback) {
				service.getMessages(loadConfig, callback);
			}
	      };
	      
	      loader = new PagingLoader<PagingLoadConfig, PagingLoadResult<MessageModel>>(rpxProxy);
	      loader.setRemoteSort(true);
	      store = new ListStore<MessageModel>(new ModelKeyProvider<MessageModel>() {
		        @Override
		        public String getKey(MessageModel item) {
		          return "" + item.getId();
		        }
		      });
	      loader.addLoadHandler(new LoadResultListStoreBinding<PagingLoadConfig, MessageModel, 
	    	    	PagingLoadResult<MessageModel>>(store));
	      view.showList(store);
    }
	public void onStart() {
		eventBus.setMessageView(view.asWidget());
		loader.load();
		
		
	}

	public void onShowList() {
		eventBus.setMessageView(view.asWidget());
		loader.load();
	}

}
